package toy.keli.edic.ui.home.components

import android.content.Context
import android.os.Handler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.Card
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import toy.keli.edic.R
import toy.keli.edic.data.plug.SpeakSet
import toy.keli.edic.ui.home.TTSListener
import toy.keli.edic.ui.navigation.NavScreen
import toy.keli.edic.view.MPopMenu
import toy.keli.edic.ui.main.extend.MText as Text

@OptIn(ExperimentalFoundationApi::class)
@Composable
@Preview
fun SpeakButton(modifier: Modifier = Modifier, clicked: Boolean=false, onButtonClick: () -> Unit={},hasText:Boolean=true,word:String="") {
    if(hasText) {
        Card(
            shape = RoundedCornerShape(8.dp),
            modifier = Modifier.clickable {
                onButtonClick()
            }
        ) {
            Column(
                verticalArrangement = Arrangement.SpaceAround,
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = modifier
                    .background(MaterialTheme.colorScheme.background)
                    .padding(8.dp)
                    .size(50.dp, 48.dp)
            ) {
                Icon(
                    painterResource(
                        id = if (clicked)
                            R.drawable.speak_off else R.drawable.speak
                    ),
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onBackground
                )
                Text(
                    text = if (clicked) "Stop" else "Speak",
                    color = MaterialTheme.colorScheme.onBackground,
                    style = MaterialTheme.typography.titleMedium
                )
            }
        }
    }else{
        val ct = LocalContext.current
        val isPriViewMode = LocalInspectionMode.current
        val events = remember{ SpeakButtonEvents(ct).apply {
            if(!isPriViewMode) {
                init()
            }
        }}
        events.word = word

        //离开的时候关闭阅读
        DisposableEffect(null) {
            onDispose {
                events.clickedState = false
            }
        }
        Icon(
            painterResource(
                id = if (events.clickedState)
                    R.drawable.speak_off else R.drawable.speak
            ),
            contentDescription = null,
            tint = MaterialTheme.colorScheme.onBackground,
            modifier = Modifier.combinedClickable(onClick = {
                events.onClick()
            }, onDoubleClick = {
                events.onDoubleClick()
            }, onLongClick = {
                events.onLongClick()
            })
        )
        events.mpm.add()
    }
}

class SpeakButtonEvents(val context:Context,var word:String=""){
    var clickedState by  mutableStateOf(false)
    var clickedType by  mutableStateOf(1)
    lateinit var ttsListener:TTSListener
    var mpm:MPopMenu =MPopMenu.SpeakConfigMenu(spConf)
//    LocalLifecycleOwner.current.lifecycle.addObserver(ttsListener)
    //刷新页面不要重复更新配置
    fun init(){
        ttsListener = TTSListener.getInstance(context)
        SpeakSet(ttsListener.getSpeech(), spConf).update()
        ttsListener.setOnCompleted {
            if (clickedType == 1)
                clickedState = false
        }
    }


    //为了复用方法在外面定义方法 不过这里有一个界面渲染重复定义的问题
    fun onDoubleClick()  {
        clickedState = !clickedState
            clickedType = 2
            Thread({
                var n = spConf.repeatNum
                while (n-- > 0 && clickedState) {
                    ttsListener.play(word)
                }
                clickedState = false
            }).start()
    }
    fun onClick() {
        clickedState = !clickedState
        clickedType = 1
        if (clickedState ) {
                ttsListener.speak(word)
        } else {
            ttsListener.stop()
        }
    }

    fun onLongClick(){
        mpm.show { k: String, v: MPopMenu.dataClass ->
            when (k) {
                "播放" ->
                    onClick()
                "重复播放" ->
                    onDoubleClick()
                else -> {
                    spConf.save(v.name, v.value)
                    SpeakSet.upMenu(mpm, spConf)
                    SpeakSet(ttsListener.getSpeech(), spConf).update()
                    if (k.startsWith("重复次数")) {
                        onDoubleClick()
                    } else {
                        onClick()
                    }
                    Handler().postDelayed({
                        mpm.visible = true
                    }, 20)
                }
            }
        }
    }
}